package com.bw.solr.solr04mlk;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.MoreLikeThisParams;
import org.apache.solr.common.util.NamedList;
import org.junit.Test;

import com.bw.solr.common.Goods;

/**
 * 相似性搜索
 * 模糊查询代码演示
 *D:\apache-tomcat-7.0.68_solr\bin
 */

public class MoreLikeThisTest {

	public static void main(String[] args) throws SolrServerException, IOException {
//		String solrUrl = "http://localhost:28080/solr/mycore";
		String solrUrl = "http://localhost:38080/solr/mycore";

		HttpSolrClient client = new HttpSolrClient(solrUrl);


		List<Goods> gList = new ArrayList<>();
		gList.add(new Goods("1000", "华为手机", 1999d, new Date(2017-1900, 3, 12), "电子"));
		gList.add(new Goods("10001", "华为手机-荣耀", 1999d, new Date(2017-1900, 3, 13), "电子"));
		gList.add(new Goods("10002", "华为手机-mate", 1999d, new Date(2017-1900, 3, 22), "电子"));
		gList.add(new Goods("1001", "童装", 33d, new Date(2017-1900, 4, 5), "服装"));
		gList.add(new Goods("1002", "红蜻蜓", 500d, new Date(2017-1900, 5, 8), "服装"));
		gList.add(new Goods("1003", "TP-Link路由器", 120d, new Date(2017-1900, 6, 20), "电子"));
		gList.add(new Goods("1004", "小米路由器", 130d, new Date(2017-1900, 7, 2), "电子"));
		gList.add(new Goods("10041", "360路由器路路路", 130d, new Date(2017-1900, 7, 2), "电子"));
		gList.add(new Goods("10042", "猎豹路由器路路", 130d, new Date(2017-1900, 7, 2), "电子"));
		gList.add(new Goods("1005", "篮球", 150d, new Date(2017-1900, 8, 3), "娱乐"));
		client.addBeans(gList);
		client.commit();
		
		
		SolrQuery q = new SolrQuery();// 建立一个新的查询
		q.setQuery("name:路由器路");
		q.set(MoreLikeThisParams.MLT, true);
		q.set(MoreLikeThisParams.MIN_DOC_FREQ, 3); // 即这个词在多少个文档中出现。
		q.set(MoreLikeThisParams.MIN_TERM_FREQ, 2); // tf(t in d)
													// 关联词出现的频率，词频率是指搜索词t 在文档d
													// 中出现的次数。文档中搜索词出现次数越多总评分也就越高。
		q.set(MoreLikeThisParams.SIMILARITY_FIELDS, "name"); // 用来计算相似性的字段

		q.set(MoreLikeThisParams.DOC_COUNT, 10); // 返回多少相似document

		System.out.println(q.toString());

		QueryResponse res = client.query(q);

		SolrDocumentList results = res.getResults();

		NamedList<?> ndl = (NamedList<?>) res.getResponse().get("moreLikeThis");
		
		
		for (int i = 0; i < ndl.size(); i++) {
			System.out.println("与" + results.get(i)  );
			System.out.println( "相似的doc有：" + ndl.getVal(i));
			System.out.println("-------------------------------");
		}
	}
}
